package com.esms.controller.score;

import com.esms.dao.EmployeeCustomVoMapper;
import com.esms.dao.EmployeeMapper;
import com.esms.po.Employee;
import com.esms.po.TKpiAssesment;
import com.esms.service.IScoreService;
import com.esms.service.TKpiAssesmentService;
import com.esms.utils.DateUtil;
import com.esms.utils.Message;
import com.esms.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ma.glasnost.orika.CustomMapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : [张丽峰]
 * @version : [v1.0]
 * @description : [可和分数处理Controller]
 * @createTime : [2022/4/7 19:27]
 */

@Controller
@RequestMapping("/employeeScore")
public class EmployeeScoreController {

    @Autowired
    private EmployeeMapper employeeMapper = null;

    @Autowired
    private EmployeeCustomVoMapper employeeCustomVoMapper;

    @Autowired
    private TKpiAssesmentService tKpiAssesmentService;

    @Autowired
    private IScoreService scoreService;

    @RequestMapping("/generateScore.do")
    @ResponseBody
    public Message generateScore() {
        try {
            scoreService.calculateTotalScore();
            return Message.success();
        } catch (Exception e) {
            return Message.fail();
        }
    }

    @RequestMapping("/findSelective.do")
    @ResponseBody
    public EmployeePages findSelective(
            @RequestParam(value = "page", defaultValue = "1") int pageNum,
            @RequestParam(value = "limit", defaultValue = "5") int limit,
            @RequestParam(value = "e_account", defaultValue = "") String e_account,
            @RequestParam(value = "e_name", defaultValue = "") String e_name,
            @RequestParam(value = "d_id", defaultValue = "0") int d_id,
            HttpSession httpSession) throws Exception {

        int eId = (Integer) httpSession.getAttribute("employeeId");
        Employee employee = employeeMapper.selectByPrimaryKey(eId);
        String cAccount = employee.geteAccount();// 当前登录员工工号,作为查询下属的入参
        //标题设置：当前日期上个月
        String befMouth = DateUtil.getBefMonthForNowDay();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("e_account", e_account);
        map.put("e_name", e_name);
        map.put("d_id", d_id);
        map.put("e_level", cAccount);
        //map.put("x_check_BeMonth", befMouth);//再加一个考核的月数
        List<EmployeeCustomVo> list = new ArrayList<EmployeeCustomVo>();
        try {
            //pageNum:起始页面  pageSize:每页的大小
            PageHelper.startPage(pageNum, limit);
            //查找条件，一定要紧跟在startPage后
            list = employeeCustomVoMapper.selectEmployeeWeekCheckSelective(map);

            for (int k = 0; k < list.size(); k++) {
                if (list.get(k).getWeekrment() != null) {
                    if (!befMouth.equals(list.get(k).getWeekrment().getxCheckBeMonth())) {
                        list.remove(k);
                        k--;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        PageInfo pageResult = new PageInfo(list);
        //设置前台需要的数据
        EmployeePages employeePages = new EmployeePages();
        employeePages.setCode(0);
        employeePages.setMsg("");
        employeePages.setCount((int) pageResult.getTotal());
        employeePages.setData(pageResult.getList());
        return employeePages;
    }


    @RequestMapping("/pageTotalScore.do")
    @ResponseBody
    public ScorePagesVo pageTotalScore(
            @RequestParam(value = "page", defaultValue = "1") int pageNum,
            @RequestParam(value = "limit", defaultValue = "5") int limit,
            @RequestParam(value = "e_account", defaultValue = "") String e_account,
            @RequestParam(value = "e_name", defaultValue = "") String e_name,
            @RequestParam(value = "d_id", defaultValue = "0") int d_id,
            @RequestParam(value = "d_gsid", defaultValue = "0") int d_gsid,
            HttpSession httpSession) throws Exception {
        try {
            e_name = new String(e_name.getBytes("ISO-8859-1"), "UTF-8");
            PageHelper.startPage(pageNum, limit);
            List<TKpiAssesment> kpiAssesments = tKpiAssesmentService.listTKpiAssesment(e_account, e_name, d_gsid, d_id);
            PageInfo pageResult = new PageInfo(kpiAssesments);
            MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
            mapperFactory.classMap(TKpiAssesment.class, TotalScoreVo.class).byDefault().customize(new CustomMapper<TKpiAssesment, TotalScoreVo>() {

                HashMap<String, String> map = new HashMap<>();
                {
                    map.put("1","行政编制");
                    map.put("2","事业编制");
                    map.put("3","聘用人员");
                }


                @Override
                public void mapAtoB(TKpiAssesment tKpiAssesment, TotalScoreVo totalScoreVo, MappingContext context) {
                    float democraticScore = Float.parseFloat(tKpiAssesment.gettAscore()) + Float.parseFloat(tKpiAssesment.gettTscore()) + Float.parseFloat(tKpiAssesment.gettSscore());
                    totalScoreVo.setDemocraticScore(String.valueOf(democraticScore));
                    totalScoreVo.setPrepareType(map.get(tKpiAssesment.getPrepareType()));
                    super.mapAtoB(tKpiAssesment, totalScoreVo, context);
                }
            }).register();
            MapperFacade facade = mapperFactory.getMapperFacade();

//            List list = facade.mapAsList(pageResult.getList(), TotalScoreVo.class);
            return new ScorePagesVo(0, "", (int) pageResult.getTotal(), facade.mapAsList(pageResult.getList(), TotalScoreVo.class));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ScorePagesVo(0, "", 0, new ArrayList<>());
    }

    @RequestMapping("/getScoreExcel.do")
    public void excel(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        List<TKpiAssesment> kpiAssesments = tKpiAssesmentService.selectListTKpiAssesment();
        System.out.println(kpiAssesments);
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet页
        HSSFSheet sheet = wb.createSheet("考核结果信息表");
        //创建标题行
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("工号");
        titleRow.createCell(1).setCellValue("姓名");
        titleRow.createCell(2).setCellValue("编制类型");
        titleRow.createCell(3).setCellValue("部门");
        titleRow.createCell(4).setCellValue("上级部门");
        titleRow.createCell(5).setCellValue("总分");
        titleRow.createCell(6).setCellValue("民主评议");
        titleRow.createCell(7).setCellValue("周记实");
        titleRow.createCell(8).setCellValue("满意度");
        titleRow.createCell(9).setCellValue("工作业绩");
        titleRow.createCell(10).setCellValue("加分项");
        titleRow.createCell(11).setCellValue("考勤");
        // 编制列表
        HashMap<String, String> map = new HashMap<>();
        map.put("1","行政编制");
        map.put("2","事业编制");
        map.put("3","聘用人员");

        //遍历将数据放到excel列中
        for (TKpiAssesment tKpiAssesment : kpiAssesments) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(tKpiAssesment.gettEaccount());
            dataRow.createCell(1).setCellValue(tKpiAssesment.gettEname());
            dataRow.createCell(2).setCellValue(map.get(tKpiAssesment.getPrepareType()));
            dataRow.createCell(3).setCellValue(tKpiAssesment.gettDname());
            dataRow.createCell(4).setCellValue(tKpiAssesment.gettDgname());
            dataRow.createCell(5).setCellValue(tKpiAssesment.gettScoresum());
            dataRow.createCell(6).setCellValue(Float.parseFloat(tKpiAssesment.gettAscore()) + Float.parseFloat(tKpiAssesment.gettTscore()) + Float.parseFloat(tKpiAssesment.gettSscore()));
            dataRow.createCell(7).setCellValue(tKpiAssesment.gettXscore());
            dataRow.createCell(8).setCellValue(tKpiAssesment.gettGscore());
            dataRow.createCell(9).setCellValue(tKpiAssesment.gettQscore());
            dataRow.createCell(10).setCellValue(tKpiAssesment.gettFscore());
            dataRow.createCell(11).setCellValue(tKpiAssesment.gettHscore());

//                dataRow.createCell(9).setCellValue(user.getCreateDateStart());
//                dataRow.createCell(10).setCellValue(user.getCreateDateEnd());

        }
            /*   // 设置下载时客户端Excel的名称
            String filename =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ".xls";
               response.setContentType("application/vnd.ms-excel");
               response.setHeader("Content-disposition", "attachment;filename=" + filename);  */

        // 设置下载时客户端Excel的名称   （上面注释的改进版本，上面的中文不支持）
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String("考核结果信息表".getBytes(), "iso-8859-1") + ".xls");


        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();


    }


}
